package com.ruoyi.web.controller.inventory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.InventoryTransaction;
import com.ruoyi.system.domain.StoreBusiness;
import com.ruoyi.system.domain.Warehouse;
import com.ruoyi.system.service.IInventoryTransactionService;
import com.ruoyi.system.service.IStoreBusinessService;
import com.ruoyi.system.service.IWarehouseService;
import com.ruoyi.system.util.AbdulEmptyUtils;
import com.ruoyi.system.util.BaseResponse;
import com.ruoyi.system.util.StoreIdUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/inventoryTransaction")
@Api(tags = "库存出入库记录管理")
public class InventoryTransactionController {

    @Autowired
    private IInventoryTransactionService inventoryTransactionService;
    @Autowired
    private StoreIdUtils storeIdUtils;

    @Autowired
    private IWarehouseService warehouseService;

    @Autowired
    private IStoreBusinessService storeBusinessService;

//    @PostMapping("/page")
//    @ApiOperation("根据ID查询库存记录")
//    public BaseResponse<IPage<InventoryTransaction>> getById(@RequestBody InventoryTransaction inventoryTransaction) {
//        LambdaQueryWrapper<InventoryTransaction> wrapper = Wrappers.lambdaQuery();
//        wrapper.eq(!AbdulEmptyUtils.isEmpty(inventoryTransaction.getId()), InventoryTransaction::getId, inventoryTransaction.getId());
//        wrapper.eq(!AbdulEmptyUtils.isEmpty(inventoryTransaction.getStoreBusinessId()), InventoryTransaction::getStoreBusinessId, inventoryTransaction.getStoreBusinessId());
//        wrapper.eq(!AbdulEmptyUtils.isEmpty(inventoryTransaction.getProductInventoryId()), InventoryTransaction::getProductInventoryId, inventoryTransaction.getProductInventoryId());
//        wrapper.eq(!AbdulEmptyUtils.isEmpty(inventoryTransaction.getStoreId()), InventoryTransaction::getStoreId, inventoryTransaction.getStoreId());
//        wrapper.eq(!AbdulEmptyUtils.isEmpty(inventoryTransaction.getType()), InventoryTransaction::getType, inventoryTransaction.getType());
//        if (!AbdulEmptyUtils.isEmpty(inventoryTransaction.getCreateTimeStart()) && !AbdulEmptyUtils.isEmpty(inventoryTransaction.getCreateTimeEnd())) {
//            wrapper.between(InventoryTransaction::getCreateTime, inventoryTransaction.getCreateTimeStart(), inventoryTransaction.getCreateTimeEnd());
//        }
//        wrapper.orderByDesc(InventoryTransaction::getUpdateTime);
//        Page<InventoryTransaction> page = inventoryTransactionService.page(new Page<>(inventoryTransaction.getPageNum(), inventoryTransaction.getPageSize()), wrapper);
//        if (!AbdulEmptyUtils.isEmpty(page.getRecords())){
//            Set<Long> warehouseIdS = page.getRecords().stream().map(InventoryTransaction::getWarehouseId).collect(Collectors.toSet()); //仓库id
//            Set<Long> storeBusinessIdS = page.getRecords().stream().map(InventoryTransaction::getStoreBusinessId).collect(Collectors.toSet()); //出入库类型
//            LambdaQueryWrapper<Warehouse> lqw = Wrappers.lambdaQuery();
//            lqw.in(Warehouse::getId, warehouseIdS);
//            List<Warehouse> warehouseList = warehouseService.list(lqw);
//            LambdaQueryWrapper<StoreBusiness> query = Wrappers.lambdaQuery();
//            query.in(StoreBusiness::getId, storeBusinessIdS);
//            List<StoreBusiness> storeBusinessList = storeBusinessService.list(query);
//            Map<Long, String> map = warehouseList.stream().collect(Collectors.toMap(Warehouse::getId, Warehouse::getWarehouseName));
//            Map<Long, String> storeBusinessMap = storeBusinessList.stream().collect(Collectors.toMap(StoreBusiness::getId, StoreBusiness::getName));
//            for (InventoryTransaction record : page.getRecords()) {
//                Long warehouseId = record.getWarehouseId();
//                if (!AbdulEmptyUtils.isEmpty(map)) {
//                    record.setWarehouseIdDesc(map.get(warehouseId));
//                }
//                Long storeBusinessId = record.getStoreBusinessId();
//                if (!AbdulEmptyUtils.isEmpty(storeBusinessList)) {
//                    record.setStoreBusinessIdDesc(storeBusinessMap.get(storeBusinessId));
//                }
//            }
//        }
//        return BaseResponse.success(page);[1,2,3,4]
//    }
    /**
     * 分页查询库存记录
     */
    @PostMapping("/page")
    @ApiOperation("分页查询库存记录")
    public BaseResponse<IPage<InventoryTransaction>> getPage(@RequestBody InventoryTransaction inventoryTransaction) {
        return BaseResponse.success(getPagedData(inventoryTransaction));
    }

    /**
     * 导出库存记录到Excel（不分页）
     */
    @PostMapping("/export")
    @ApiOperation("导出库存记录")
    public void exportData(@RequestBody InventoryTransaction inventoryTransaction, HttpServletResponse response) {
        List<InventoryTransaction> records = getAllData(inventoryTransaction);
        ExcelUtil<InventoryTransaction> util = new ExcelUtil<>(InventoryTransaction.class);
        util.exportExcel(response, records, "库存交易记录");
    }

    /**
     * 获取分页数据并填充关联信息
     */
    private IPage<InventoryTransaction> getPagedData(InventoryTransaction inventoryTransaction) {
        LambdaQueryWrapper<InventoryTransaction> wrapper = Wrappers.lambdaQuery();
        buildCommonConditions(wrapper, inventoryTransaction);

        Page<InventoryTransaction> page = inventoryTransactionService.page(
                new Page<>(inventoryTransaction.getPageNum(), inventoryTransaction.getPageSize()), wrapper);

        enrichWithRelatedData(page);

        return page;
    }

    /**
     * 获取所有数据用于导出（不分页）
     */
    private List<InventoryTransaction> getAllData(InventoryTransaction inventoryTransaction) {
        LambdaQueryWrapper<InventoryTransaction> wrapper = Wrappers.lambdaQuery();
        buildCommonConditions(wrapper, inventoryTransaction);

        List<InventoryTransaction> list = inventoryTransactionService.list(wrapper);

        enrichWithRelatedDataForList(list);

        return list;
    }

    /**
     * 构建通用查询条件
     */
    private void buildCommonConditions(LambdaQueryWrapper<InventoryTransaction> wrapper, InventoryTransaction inventoryTransaction) {
        wrapper.eq(!AbdulEmptyUtils.isEmpty(inventoryTransaction.getId()), InventoryTransaction::getId, inventoryTransaction.getId());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(inventoryTransaction.getStoreBusinessId()), InventoryTransaction::getStoreBusinessId, inventoryTransaction.getStoreBusinessId());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(inventoryTransaction.getProductInventoryId()), InventoryTransaction::getProductInventoryId, inventoryTransaction.getProductInventoryId());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(inventoryTransaction.getStoreId()), InventoryTransaction::getStoreId, inventoryTransaction.getStoreId());
        wrapper.eq(!AbdulEmptyUtils.isEmpty(inventoryTransaction.getType()), InventoryTransaction::getType, inventoryTransaction.getType());

        if (!AbdulEmptyUtils.isEmpty(inventoryTransaction.getCreateTimeStart()) && !AbdulEmptyUtils.isEmpty(inventoryTransaction.getCreateTimeEnd())) {
            wrapper.between(InventoryTransaction::getCreateTime, inventoryTransaction.getCreateTimeStart(), inventoryTransaction.getCreateTimeEnd());
        }

        wrapper.orderByDesc(InventoryTransaction::getUpdateTime);
    }

    /**
     * 补充关联字段描述信息（分页使用）
     */
    private void enrichWithRelatedData(Page<InventoryTransaction> page) {
        List<InventoryTransaction> records = page.getRecords();
        enrichWithRelatedDataForList(records);
    }

    /**
     * 补充关联字段描述信息（列表使用）
     */
    private void enrichWithRelatedDataForList(List<InventoryTransaction> records) {
        if (AbdulEmptyUtils.isEmpty(records)) {
            return;
        }

        Set<Long> warehouseIdS = records.stream()
                .map(InventoryTransaction::getWarehouseId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        Set<Long> storeBusinessIdS = records.stream()
                .map(InventoryTransaction::getStoreBusinessId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        Map<Long, String> warehouseMap = Collections.emptyMap();
        Map<Long, String> storeBusinessMap = Collections.emptyMap();

        if (!warehouseIdS.isEmpty()) {
            List<Warehouse> warehouseList = warehouseService.list(Wrappers.<Warehouse>lambdaQuery().in(Warehouse::getId, warehouseIdS));
            warehouseMap = warehouseList.stream()
                    .collect(Collectors.toMap(Warehouse::getId, Warehouse::getWarehouseName));
        }

        if (!storeBusinessIdS.isEmpty()) {
            List<StoreBusiness> storeBusinessList = storeBusinessService.list(Wrappers.<StoreBusiness>lambdaQuery().in(StoreBusiness::getId, storeBusinessIdS));
            storeBusinessMap = storeBusinessList.stream()
                    .collect(Collectors.toMap(StoreBusiness::getId, StoreBusiness::getName));
        }

        for (InventoryTransaction record : records) {
            Long warehouseId = record.getWarehouseId();
            if (warehouseMap.containsKey(warehouseId)) {
                record.setWarehouseIdDesc(warehouseMap.get(warehouseId));
            }

            Long storeBusinessId = record.getStoreBusinessId();
            if (storeBusinessMap.containsKey(storeBusinessId)) {
                record.setStoreBusinessIdDesc(storeBusinessMap.get(storeBusinessId));
            }
        }
    }
}

